package com.example.mateproject.ui.adapter

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ObjectAnimator
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.AccelerateInterpolator
import android.view.animation.DecelerateInterpolator
import android.widget.ImageView
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.mateproject.MainActivity
import com.example.mateproject.R
import com.example.mateproject.ui.bean.MateBean
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.util.Collections
import java.util.Random


class MainAdapter(val context: ComponentActivity) : RecyclerView.Adapter<MainAdapter.MainViewHolder>(),
    LifecycleOwner {

    private var mData = arrayListOf<MateBean>()
    private val picName = arrayOf("ic_pic1","ic_pic2","ic_pic3","ic_pic4","ic_pic5","ic_pic6","ic_pic7","ic_pic8","ic_pic9","ic_pic10","ic_pic11","ic_pic12","ic_pic13","ic_pic14")
    private val mRegistry = LifecycleRegistry(this)
    private val cardNum = 12
    private var clickItemName = ""

    init {
        setData()
    }

    fun setData(){
        mData.clear()
        clickItemName = ""
        var random = true
        var indexs = arrayListOf<Int>()
        var positions = arrayListOf<Int>()
        while (random) {
            val position = Random().nextInt(picName.size)
            if (!positions.contains(position)) {
                positions.add(position)
                for (i in 0..1) {
                    if (indexs.size < cardNum) {
                        indexs.add(position)
                    } else {
                        random = false
                    }
                }
            }
        }
        indexs.shuffle()
        indexs.forEach {
            val mateBean = MateBean(picName[it], picName[it])
            mData.add(mateBean)
        }
        notifyDataSetChanged()
    }

    class MainViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val ivBack: ImageView = itemView.findViewById<ImageView>(R.id.iv_back1)
        val ivPic: ImageView = itemView.findViewById<ImageView>(R.id.iv_pic1)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MainViewHolder {
        return MainViewHolder(
            LayoutInflater.from(context)
                .inflate(R.layout.main_list_item_view, null, false)
        )
    }

    override fun getItemCount(): Int {
        return mData.size
    }

    override fun onBindViewHolder(holder: MainViewHolder, position: Int) {
        val bean:MateBean = mData[position]
        val resourceId = context.resources.getIdentifier(bean.path, "mipmap", context.packageName)
        Glide.with(context)
            .load(resourceId) // 加载本地资源时直接传入资源ID
            .placeholder(R.drawable.ic_loading) // 可选：设置占位图
            .error(R.drawable.ic_load_failed) // 可选：设置加载失败时显示的图片
            .into(holder.ivPic) // 将图片加载到指定的ImageView中
        val visToInvis = ObjectAnimator.ofFloat(holder.ivBack, "rotationY", 0f, 90f)
        visToInvis.setDuration(500)
        visToInvis.interpolator = AccelerateInterpolator()
        val invisToVis = ObjectAnimator.ofFloat(holder.ivBack, "rotationY",-90f, 0f)
        invisToVis.setDuration(500)
        invisToVis.interpolator = DecelerateInterpolator()
        visToInvis.addListener(object : AnimatorListenerAdapter() {
            override fun onAnimationEnd(anim: Animator) {
                holder.ivBack?.visibility = View.GONE
                holder.ivPic?.visibility = View.VISIBLE
                bean.front = true
            }
        })
        invisToVis.addListener(object : AnimatorListenerAdapter() {
            override fun onAnimationEnd(anim: Animator) {
                holder.ivBack?.visibility = View.VISIBLE
                holder.ivPic?.visibility = View.GONE
                bean.front = true
            }
        })
        if (bean.front) {
            holder.ivBack?.visibility = View.VISIBLE
            holder.ivPic?.visibility = View.GONE
        }else{
            holder.ivBack?.visibility = View.GONE
            holder.ivPic?.visibility = View.VISIBLE
        }
        holder.ivBack.setOnClickListener {
            visToInvis.start()
            if (clickItemName.isEmpty()) {
                clickItemName = bean.name
            } else {
                if (clickItemName == bean.name) {
                    (context as MainActivity).success()
                    Toast.makeText(context, "恭喜你，成功啦！", Toast.LENGTH_LONG).show()
                } else {
                    (context as MainActivity).failed()
                    Toast.makeText(context, "很遗憾，失败了！", Toast.LENGTH_LONG).show()
                }
            }
        }
        lifecycleScope.launch {
            delay(1000)
            invisToVis.start()
        }
    }

    override val lifecycle: Lifecycle
        get() = mRegistry
}